#pragma once

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;

    class Complier
    {
        public:
        Complier()
        {}
        ~Complier()
        {}
        static bool Compile(const std::string &file_name)
        {
            pid_t pid = fork();
            if(pid <0)
            {
                LOG(ERROR) << "创建子进程失败" << "\n";
                return false;
            }
            else if(pid ==0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompilerError(file_name).c_str(),O_CREAT|O_WRONLY,0644);
                if(_stderr < 0){
                    LOG(WARNING) << "创建stderr文件失败" << "\n";
                    exit(1);
                }

                dup2(_stderr,2);

                //子进程完成对代码的编译功能
                if(execlp("g++","g++","-o",PathUtil::Exe(file_name).c_str(),\
                PathUtil::Src(file_name).c_str(),"-std=c++11","-D","COMPILER_ONLINE",nullptr)==-1)
                {
                    perror("Compilation failed");
                }
                
                LOG(ERROR) << "启动编译器g++失败" << "\n";
                exit(2);
            }
            else
            {
                waitpid(pid,nullptr,0);
                //编译是否成功,判断是否生成可执行程序
                if(FileUtil::IsFileExists(PathUtil::Exe(file_name)))
                {
                    LOG(INFO) << PathUtil::Src(file_name) << " 编译成功" << "\n";
                    return true;
                }

                LOG(ERROR) << "编译失败,形成可执行程序失败" << "\n";
            }

            return false;
        }
    };
}